<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMindArchiveStore } from '../stores/mindArchiveStore'
import { useContainerStore } from '../stores/containerStore'
import { ElMessage } from 'element-plus'
import { Calendar, Document, Edit, Delete, Timer } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const mindArchiveStore = useMindArchiveStore()
const containerStore = useContainerStore()

// 获取路由参数中的存档ID
const archiveId = route.params.id

// 当前存档
const archive = computed(() => {
  return mindArchiveStore.archives.find(a => a.id === archiveId)
})

// 关联的容器
const relatedContainer = computed(() => {
  if (!archive.value || !archive.value.containerId) return null
  return containerStore.containers.find(c => c.id === archive.value.containerId)
})

// 添加备注
const newNote = ref('')

function addNote() {
  if (newNote.value.trim()) {
    mindArchiveStore.addArchiveNote(archiveId, newNote.value)
    newNote.value = ''
    
    // 显示成功消息
    ElMessage({
      message: '备注添加成功',
      type: 'success'
    })
  }
}

// 恢复存档
const restorationNote = ref('')
const restoreDialogVisible = ref(false)

function openRestoreDialog() {
  restorationNote.value = ''
  restoreDialogVisible.value = true
}

function confirmRestore() {
  mindArchiveStore.restoreArchive(archiveId, restorationNote.value)
  restoreDialogVisible.value = false
  
  // 显示成功消息
  ElMessage({
    message: '思维存档已恢复',
    type: 'success'
  })
}

// 开始容器专注
const startContainerForm = ref({
  title: '',
  description: '',
  category: '',
  estimatedTime: 30
})

const startContainerDialogVisible = ref(false)

function openStartContainerDialog() {
  // 使用存档信息预填充容器表单
  if (archive.value) {
    startContainerForm.value.title = archive.value.title
    startContainerForm.value.description = archive.value.description || ''
    
    // 如果存档有标签，使用第一个标签作为分类
    if (archive.value.tags && archive.value.tags.length > 0) {
      startContainerForm.value.category = archive.value.tags[0]
    }
  }
  
  startContainerDialogVisible.value = true
}

function confirmStartContainer() {
  containerStore.createContainer(startContainerForm.value)
  startContainerDialogVisible.value = false
  
  // 显示成功消息
  ElMessage({
    message: '容器专注已开始',
    type: 'success'
  })
  
  // 跳转到容器页面
  router.push('/container')
}

// 返回存档库
function backToLibrary() {
  router.push('/mind-archive-library')
}

// 分享到社区
function shareToCommunitiy() {
  router.push({
    path: '/campfire/create',
    query: {
      archiveId: archive.value.id
    }
  })
}

// 格式化日期
function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 获取标签颜色
function getTagColor(tag) {
  const colorMap = {
    '工作': 'success',
    '学习': 'primary',
    '项目': 'warning',
    '创意': 'danger',
    '问题': 'info',
    '决策': 'success',
    '灵感': 'warning'
  }
  
  return colorMap[tag] || ''
}
</script>

<template>
  <div v-if="archive" class="mind-archive-detail-container">
    <div class="page-header">
      <el-button @click="backToLibrary" plain>
        返回存档库
      </el-button>
      
      <el-button 
        v-if="archive.status === 'active'"
        type="success" 
        @click="openRestoreDialog"
      >
        恢复存档
      </el-button>
      
      <el-button 
        type="primary" 
        @click="openStartContainerDialog"
      >
        <el-icon><Timer /></el-icon>
        开始容器专注
      </el-button>
      
      <el-button 
        type="success" 
        @click="shareToCommunitiy"
      >
        分享到社区
      </el-button>
    </div>
    
    <el-card class="archive-detail-card">
      <template #header>
        <div class="card-header">
          <h2 class="archive-title">{{ archive.title }}</h2>
          <el-tag 
            v-if="archive.status === 'active'" 
            type="success" 
            effect="plain"
          >
            活动中
          </el-tag>
          <el-tag 
            v-else 
            type="info" 
            effect="plain"
          >
            已恢复
          </el-tag>
        </div>
      </template>
      
      <div class="archive-meta">
        <div class="meta-item">
          <el-icon><Calendar /></el-icon>
          <span>创建于：{{ formatDate(archive.archiveTime) }}</span>
        </div>
        
        <div v-if="archive.restorationTime" class="meta-item">
          <el-icon><Calendar /></el-icon>
          <span>恢复于：{{ formatDate(archive.restorationTime) }}</span>
        </div>
      </div>
      
      <div class="archive-tags">
        <el-tag 
          v-for="tag in archive.tags" 
          :key="tag"
          :type="getTagColor(tag)"
          effect="light"
          class="archive-tag"
        >
          {{ tag }}
        </el-tag>
      </div>
      
      <div class="archive-section">
        <h3>详细描述</h3>
        <p class="archive-content">{{ archive.description || '无详细描述' }}</p>
      </div>
      
      <div class="archive-section">
        <h3>当前卡点</h3>
        <p class="archive-content blocking-point">{{ archive.blockingPoint }}</p>
      </div>
      
      <div v-if="relatedContainer" class="archive-section">
        <h3>关联预备容器</h3>
        <el-card class="related-container-card">
          <div class="container-title">{{ relatedContainer.title }}</div>
          <div class="container-meta">
            <span>分类：{{ relatedContainer.category }}</span>
            <span>状态：{{ relatedContainer.status === 'active' ? '进行中' : '已完成' }}</span>
          </div>
          <div v-if="relatedContainer.description" class="container-description">
            {{ relatedContainer.description }}
          </div>
        </el-card>
      </div>
      
      <div v-if="archive.restorationNote" class="archive-section">
        <h3>恢复备注</h3>
        <p class="archive-content">{{ archive.restorationNote }}</p>
      </div>
    </el-card>
    
    <el-card class="notes-card">
      <template #header>
        <div class="card-header">
          <h3>存档备注</h3>
        </div>
      </template>
      
      <div v-if="archive.notes && archive.notes.length > 0" class="notes-list">
        <div 
          v-for="note in archive.notes" 
          :key="note.id" 
          class="note-item"
        >
          <div class="note-header">
            <div class="note-time">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(note.createTime) }}
            </div>
          </div>
          <div class="note-content">{{ note.content }}</div>
        </div>
      </div>
      
      <div v-else class="no-notes">
        <el-empty description="暂无备注" />
      </div>
      
      <div v-if="archive.status === 'active'" class="add-note-form">
        <h4>添加新备注</h4>
        <el-input 
          v-model="newNote" 
          type="textarea" 
          placeholder="记录新的想法或进展" 
          :rows="3" 
        />
        <el-button 
          type="primary" 
          @click="addNote" 
          class="add-note-button"
          :disabled="!newNote.trim()"
        >
          添加备注
        </el-button>
      </div>
    </el-card>
    
    <!-- 恢复存档对话框 -->
    <el-dialog
      v-model="restoreDialogVisible"
      title="恢复思维存档"
      width="500px"
    >
      <p>确定要恢复「{{ archive.title }}」这个思维存档吗？</p>
      
      <el-form>
        <el-form-item label="恢复备注">
          <el-input 
            v-model="restorationNote" 
            type="textarea" 
            placeholder="记录恢复后的思考进展" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="restoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRestore">确认恢复</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 开始容器专注对话框 -->
    <el-dialog
      v-model="startContainerDialogVisible"
      title="开始容器专注"
      width="40%"
    >
      <el-form :model="startContainerForm" label-position="top">
        <el-form-item label="容器名称" required>
          <el-input v-model="startContainerForm.title" placeholder="容器名称" />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="startContainerForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="容器描述" 
          />
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select v-model="startContainerForm.category" placeholder="选择分类" style="width: 100%">
            <el-option label="工作" value="工作" />
            <el-option label="学习" value="学习" />
            <el-option label="阅读" value="阅读" />
            <el-option label="写作" value="写作" />
            <el-option label="思考" value="思考" />
            <el-option label="运动" value="运动" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="预估时间（分钟）">
          <el-input-number 
            v-model="startContainerForm.estimatedTime" 
            :min="5" 
            :max="480" 
            :step="5" 
            style="width: 100%" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="startContainerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStartContainer">开始专注</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
  <div v-else class="not-found">
    <el-empty description="未找到存档" />
    <el-button @click="backToLibrary">返回存档库</el-button>
  </div>
</template>

<style scoped>
.mind-archive-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.archive-detail-card,
.notes-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.archive-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.archive-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.archive-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.archive-section {
  margin-bottom: 25px;
}

.archive-section h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #303133;
  font-weight: 500;
}

.archive-content {
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

.blocking-point {
  color: #F56C6C;
  font-weight: 500;
}

.related-container-card {
  background-color: #f8f9fa;
  border: 1px solid #ebeef5;
}

.container-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #303133;
}

.container-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.container-description {
  color: #606266;
}

.notes-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.note-item {
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f9fa;
  border-left: 3px solid #409EFF;
}

.note-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.note-time {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.note-content {
  color: #303133;
  line-height: 1.6;
  white-space: pre-line;
}

.no-notes {
  margin: 30px 0;
}

.add-note-form {
  margin-top: 30px;
}

.add-note-form h4 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #303133;
}

.add-note-button {
  margin-top: 10px;
}

.not-found {
  text-align: center;
  padding: 50px 0;
}
</style>